﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Framework.IService;
using FantastPlatform.Framework;
using Newtonsoft.Json;

namespace FantastPlatform.Community.UI.Service
{
    /// <summary>
    /// BaseInfoService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class BaseInfoService : System.Web.Services.WebService
    {

        [WebMethod]
        public void SearchStreet(string code, string start, string limit)
        {
            try
            {
                int totalRecords = 0;
                int pageSize = int.Parse(limit);
                int pageNum = (int.Parse(start) / pageSize) + 1;
                IStreetService streetService = ServiceFactory.CreateService<IStreetService>();
                IList<IStreet> streets = streetService.SearchStreet(code, pageNum, pageSize, out totalRecords);
                ReturnList(totalRecords,streets);
            }
            catch (Exception ex)
            { 
                ReturnErrorMessage(ex.Message);
            }
        }
        protected void ReturnErrorMessage(string message)
        {
            Response.Clear();
            Response.Write("{'success':'false','message':'" + message.Replace("\r\n", "").Replace("'", "") + "'}");
            Response.End();
        }

        protected void ReturnList(int totalRecords, Object objects)
        {
            //StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
            //JsonSerializer jsonSerializer = new JsonSerializer();
            //jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            //using (JsonWriter jsonWriter = new JsonTextWriter(sw))
            //{
            //    jsonWriter.Formatting = Formatting.Indented;
            //    jsonSerializer.Serialize(jsonWriter, objects);
            //}
            //string jsonStrs = "{'totalCount':'" + totalRecords.ToString() + "','topics':" + sw.ToString() + "}";

            string jsonStrs = JsonConvert.SerializeObject(objects);
            jsonStrs = "{'totalCount':'" + totalRecords.ToString() + "','topics':" + jsonStrs.ToString() + "}";

            Response.Write(jsonStrs);
           
        }
        protected HttpResponse Response
        {
            get
            {
                return Context.Response;
            }
        }
    }
}
